<?php
ini_set('date.timezone','Asia/Shanghai');
//error_reporting(E_ERROR); 

//require_once '../sql.php';
require_once (dirname(__FILE__) . "/../../common.inc.php");
require_once DEDEDATA."/payment/wpay.php"; 
require_once "WxPay.Api.php";
require_once 'WxPay.Notify.php';
require_once 'log.php';  

//初始化日志

$logHandler= new CLogFileHandler("../logs/".date('Y-m-d-H-i-s').'.log');
$log = Log::Init($logHandler, 15); 
 
class PayNotifyCallBack extends WxPayNotify
{
	//查询订单
	var $xsuccess='';
	var $mid;
	public function Queryorder($transaction_id)
	{
		$input = new WxPayOrderQuery();
		$input->SetTransaction_id($transaction_id);
		$result = WxPayApi::orderQuery($input);
		Log::DEBUG("query:" . json_encode($result));
		if(array_key_exists("return_code", $result)
			&& array_key_exists("result_code", $result)
			&& $result["return_code"] == "SUCCESS"
			&& $result["result_code"] == "SUCCESS")
		{
			return true;
		}
		//print_r($result);
		return false;
	}
	
	//重写回调处理函数
	public function NotifyProcess($data, &$msg)
	{
		global $dsql;
		Log::DEBUG("call back:" . json_encode($data));
		$notfiyOutput = array();
		
		if(!array_key_exists("transaction_id", $data)){
			$msg = "输入参数不正确";
			return false;
		}
		//查询订单，判断订单真实性
		if(!$this->Queryorder($data["transaction_id"])){
			$msg = "订单查询失败";
			return false;
		}
		
		Log::DEBUG($data['transaction_id'].'xiexiang');
		$orderID=$data['out_trade_no'];
		$wx_orderID=$data['transaction_id'];
		 $sql = "UPDATE `#@__shops_orders` SET `state`='1' WHERE `oid`='$orderID'";
		 
        if(preg_match ("/S-P[0-9]+RN[0-9]/",$orderID)) {
            //检查支付金额是否相符
            $row = $dsql->GetOne("SELECT * FROM #@__shops_orders WHERE oid = '{$orderID}'");
            //if ($row['priceCount'] != $data['cash_fee'])
            //{
            //    Log::DEBUG("支付失败，支付金额与商品总价不相符");
           // }
            $this->mid = $row['userid'];
            $ordertype="goods";
        }else if (preg_match ("/M[0-9]+T[0-9]+RN[0-9]/", $orderID)){
            $row = $dsql->GetOne("SELECT * FROM #@__member_operation WHERE buyid = '{$orderID}'");
            //获取订单信息，检查订单的有效性
            if(!is_array($row)||$row['sta']==2) {
				Log::DEBUG("您的订单已经处理，请不要重复提交!");
			}elseif($row['money'] != $_GET['total_fee']){
				Log::DEBUG("支付失败，支付金额与商品总价不相符!");
			} 
			
            $ordertype = "member";
            $product =    $row['product'];
            $pname= $row['pname'];
            $pid=$row['pid'];
            $this->mid = $row['mid'];
        }else{
			Log::DEBUG("什么情况？");
		}
		
		
		if($data['result_code']=='SUCCESS' && $dsql->ExecuteNoneQuery($sql)){
		      Log::DEBUG("UPDATE `#@__shops_orders` SET `state`='1' WHERE `oid`='$orderID' ");
			  $this->xsuccess=$data['result_code'];
			 //$dsql->ExecuteNoneQuery(" UPDATE `#@__baoming` SET fk_state=1,zf_orderID='$wx_orderID',zf_fangshi='微信支付' WHERE orderID='$orderID' ");
			if($ordertype=="goods"){ 
				Log::DEBUG("成功了123");
                if($this->success_db($orderID))   echo "<script type='text/javascript'>alert('支付成功·正在跳转会员中心...');window.location.href  = '/member/';	</script>";
                else  return $msg = "支付失败！<br> <a href='/'>返回主页</a> <a href='/member'>会员中心</a>";
            } else if ( $ordertype=="member" ) {
				Log::DEBUG("成功了456");
                $oldinf = $this->success_mem($orderID,$pname,$product,$pid);
				 echo "<script type='text/javascript'>alert('".$oldinf."');window.location.href  = '/member/';	</script>";
                //return $msg = "<font color='red'>".."</font><br> <a href='/'>返回主页</a> <a href='/member'>会员中心</a>";
            }else{
				Log::DEBUG("123什么情况？");
			}
			
			 
			 
			/** echo "<script type='text/javascript'>alert('支付成功·正在跳转会员中心...');window.location.href  = '/member/';	</script>";
			 ShowMsg("支付成功!<br> <a href='/'>返回主页</a> <a href='/member'>会员中心</a>", "javascript:;", 0, 3000);**/
			return true;
		}else{
			Log::DEBUG("支付失败 ");
		 	ShowMsg("支付失败！<br> <a href='/'>返回主页</a> <a href='/member'>会员中心</a>", "javascript:;", 0, 3000);
			return false;
		}
		//Log::DEBUG(" UPDATE `#@__baoming` SET fk_state=1,zf_orderID='$wx_orderID',zf_fangshi='微信支付' WHERE orderID='$orderID' ");
		
	}
	
  /*处理物品交易*/
    function success_db($order_sn)
    {
		global $dsql;
        //获取订单信息，检查订单的有效性
        $row = $dsql->GetOne("SELECT state FROM #@__shops_orders WHERE oid='$order_sn' ");
        if($row['state'] > 0)
        {
            return TRUE;
        }    
        /* 改变订单状态_支付成功 */
        $sql = "UPDATE `#@__shops_orders` SET `state`='1' WHERE `oid`='$order_sn'";
        if($dsql->ExecuteNoneQuery($sql))
        {
            Log::DEBUG("verify_success,订单号:".$order_sn); //将验证结果存入文件
            return TRUE;
        } else {
            Log::DEBUG("verify_failed,订单号:".$order_sn);//将验证结果存入文件
            return FALSE;
        }
    }

    /*处理点卡，会员升级*/
    function success_mem($order_sn,$pname,$product,$pid)
    {
		global $dsql;
        //更新交易状态为已付款
        $sql = "UPDATE `#@__member_operation` SET `sta`='1' WHERE `buyid`='$order_sn' AND `mid`='".$this->mid."'";
        $dsql->ExecuteNoneQuery($sql);

        /* 改变点卡订单状态_支付成功 */
        if($product=="card")
        {
            $row = $dsql->GetOne("SELECT cardid FROM #@__moneycard_record WHERE ctid='$pid' AND isexp='0' ");;
            //如果找不到某种类型的卡，直接为用户增加金币
            if(!is_array($row))
            {
                $nrow = $dsql->GetOne("SELECT num FROM #@__moneycard_type WHERE pname = '{$pname}'");
                $dnum = $nrow['num'];
                $sql1 = "UPDATE `#@__member` SET `money`=money+'{$nrow['num']}' WHERE `mid`='".$this->mid."'";
                $oldinf ="已经充值了".$nrow['num']."金币到您的帐号！";
            } else {
                $cardid = $row['cardid'];
                $sql1=" UPDATE #@__moneycard_record SET uid='".$this->mid."',isexp='1',utime='".time()."' WHERE cardid='$cardid' ";
                $oldinf='您的充值密码是：<font color="green">'.$cardid.'</font>';
            }
            //更新交易状态为已关闭
            $sql2=" UPDATE #@__member_operation SET sta=2,oldinfo='$oldinf' WHERE buyid='$order_sn'";
            if($dsql->ExecuteNoneQuery($sql1) && $dsql->ExecuteNoneQuery($sql2))
            {
                Log::DEBUG("verify_success,订单号:".$order_sn); //将验证结果存入文件
                return $oldinf;
            } else {
                Log::DEBUG("verify_failed,订单号:".$order_sn);//将验证结果存入文件
                return "支付失败！";
            }
        /* 改变会员订单状态_支付成功 */
        } else if ( $product=="member" ){
            $row = $dsql->GetOne("SELECT rank,exptime FROM #@__member_type WHERE aid='$pid' ");
            $rank = $row['rank'];
            $exptime = $row['exptime'];
            /*计算原来升级剩余的天数*/
            $rs = $dsql->GetOne("SELECT uptime,exptime FROM #@__member WHERE mid='".$this->mid."'");
            if($rs['uptime']!=0 && $rs['exptime']!=0 ) 
            {
                $nowtime = time();
                $mhasDay = $rs['exptime'] - ceil(($nowtime - $rs['uptime'])/3600/24) + 1;
                $mhasDay=($mhasDay>0)? $mhasDay : 0;
            }
            //获取会员默认级别的金币和积分数
            $memrank = $dsql->GetOne("SELECT money,scores FROM #@__arcrank WHERE rank='$rank'");
            //更新会员信息
            $sql1 =  " UPDATE #@__member SET rank='$rank',money=money+'{$memrank['money']}',
                       scores=scores+'{$memrank['scores']}',exptime='$exptime'+'$mhasDay',uptime='".time()."' 
                       WHERE mid='".$this->mid."'";
            //更新交易状态为已关闭
            $sql2=" UPDATE #@__member_operation SET sta='2',oldinfo='会员升级成功!' WHERE buyid='$order_sn' ";
            if($dsql->ExecuteNoneQuery($sql1) && $dsql->ExecuteNoneQuery($sql2))
            {
                Log::DEBUG("verify_success,订单号:".$order_sn); //将验证结果存入文件
                return "会员升级成功！";
            } else {
                Log::DEBUG("verify_failed,订单号:".$order_sn);//将验证结果存入文件
                return "会员升级失败！";
            }
        }    
    }
	
	
	
}

//Log::DEBUG("begin notify 失败了");
$notify = new PayNotifyCallBack();
$notify->Handle(false);


